use std::collections::HashMap;

#[derive(Debug)]
pub enum CacheValue {
    Int(i32),
    Float(f64),
    Text(String),
    Bool(bool)
}

pub struct ResourceCache {
    data: HashMap<String, Option<CacheValue>>,
}

impl ResourceCache {
    pub fn new() -> Self {
        ResourceCache { data: HashMap::new() }
    }

    pub fn add(&mut self, key: String, value: Option<CacheValue>) {
        self.data.insert(key, value);
    }

    pub fn get(&self, key: &str) -> Option<&CacheValue> {
        self.data.get(key).and_then(|opt| opt.as_ref())
    }

    pub fn has(&self, key: &str) -> bool {
        self.data.contains_key(key)
    }   
}

fn main() {
    let mut cache = ResourceCache::new();
    // 添加不同类型的数据
    cache.add("number".to_string(), Some(CacheValue::Int(42)));
    cache.add("pi".to_string(), Some(CacheValue::Float(3.14)));
    cache.add("greeting".to_string(), Some(CacheValue::Text(String::from("Hello"))));
    cache.add("flag".to_string(), Some(CacheValue::Bool(true)));
    cache.add("empty".to_string(), None);

    // 安全提取各种类型的值
    if let Some(value) = cache.get("number") {
        match value {
            CacheValue::Int(n) => println!("Got integer: {}", n),
            _ => println!("Not an integer"),
        }
    }

    if let Some(value) = cache.get("pi") {
        match value {
            CacheValue::Float(f) => println!("Got float: {}", f),
            _ => println!("Not a float"),
        }
    }

    if let Some(value) = cache.get("greeting") {
        match value {
            CacheValue::Text(s) => println!("Got text: {}", s),
            _ => println!("Not a text"),
        }
    }

    if let Some(value) = cache.get("flag") {
        match value {
            CacheValue::Bool(b) => println!("Got boolean: {}", b),
            _ => println!("Not a boolean"),
        }
    }

    // 更简洁的if let语法
    if let Some(CacheValue::Int(n)) = cache.get("number") {
        println!("简洁写法获取整数: {}", n);
    }
}